package com.wlts.wzy.KSOrderModule.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.linkedmall.model.v20180116.*;
import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.kuaishou.merchant.open.api.client.AccessTokenKsMerchantClient;
import com.kuaishou.merchant.open.api.request.KsMerchantOrderDeliverRequest;
import com.kuaishou.merchant.open.api.request.KsMerchantRefundApproveRequest;
import com.kuaishou.merchant.open.api.request.KsMerchantRefundDetailRequest;
import com.kuaishou.merchant.open.api.response.KsMerchantOrderDeliverResponse;
import com.kuaishou.merchant.open.api.response.KsMerchantRefundApproveResponse;
import com.kuaishou.merchant.open.api.response.KsMerchantRefundDetailResponse;
import com.wlts.wzy.Base.BaseEntity;
import com.wlts.wzy.KSOrderModule.entity.KsExpressCode;
import com.wlts.wzy.KSOrderModule.entity.KsOrders;
import com.wlts.wzy.KSOrderModule.service.IKsExpressCodeService;
import com.wlts.wzy.KSOrderModule.service.IKsOrdersService;
import com.wlts.wzy.KSUserModule.entity.KsOauth;
import com.wlts.wzy.KSUserModule.entity.KsStoreUser;
import com.wlts.wzy.KSUserModule.service.IKsOauthService;
import com.wlts.wzy.KSUserModule.service.IKsStoreUserService;
import com.wlts.wzy.KSUserModule.util.KsConfig;
import com.wlts.wzy.LMGoodsModule.entity.LmAddress;
import com.wlts.wzy.LMGoodsModule.entity.LmSelfGoods;
import com.wlts.wzy.LMGoodsModule.service.ILmAddressService;
import com.wlts.wzy.LMGoodsModule.service.ILmSelfGoodsService;
import com.wlts.wzy.Result.Result;
import com.wlts.wzy.api.request.ks.*;
import com.wlts.wzy.api.request.lm.*;
import com.wlts.wzy.api.response.lm.GetLmOrderExpressResponse;
import com.wlts.wzy.api.response.lm.RefundApplicationDetailResponse;
import com.wlts.wzy.api.vo.DeliveryAddress;
import com.wlts.wzy.api.vo.KsVO.KsOrdersAddress;
import com.wlts.wzy.api.vo.KsVO.KsOrdersGoodsVO;
import com.wlts.wzy.configBean.KsConfig.KsConfigInfo;
import com.wlts.wzy.configBean.LmConfig.LmConfig;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.expand.MyPage;
import com.wlts.wzy.redisLockModule.config.DistributedLocker;
import com.wlts.wzy.util.AddressResolutionUtil;
import com.wlts.wzy.util.CopyUtils;
import com.wlts.wzy.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.wlts.wzy.KSOrderModule.util.PutOrdersToLmUtil.enableOrder;
import static com.wlts.wzy.configBean.LmConfig.LmConfig.client;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author zhiyong
 * @since 2021-02-02
 */
@Api(tags = "快手订单表 前端控制器")
@RestController
@RequestMapping("/KSOrderModule/ks-orders")
public class KsOrdersController {
    @Autowired
    private IKsOrdersService ksOrdersService;
    @Autowired
    private IKsStoreUserService ksStoreUserService;
    @Autowired
    private ILmSelfGoodsService lmSelfGoodsService;
    @Autowired
    private ILmAddressService lmAddressService;
    @Autowired
    private KsConfig ksConfig;
    @Autowired
    private DistributedLocker distributedLocker;
    @Autowired
    private IKsOauthService ksOauthService;
    @Autowired
    private IKsExpressCodeService ksExpressCodeService;

    @ApiOperation(value = "获得我的订单")
    @RequestMapping(value = "getMyKsOrders", method = RequestMethod.POST)
    public Result<MyPage<KsOrders>> getMyKsOrders(@RequestBody GetMyKsOrdersRequest request) {

        // System.out.println(request.toString());

        MyLambdaQueryWrapper<KsStoreUser> userWrapper = new MyLambdaQueryWrapper<>();

        userWrapper.eq(KsStoreUser::getUuid, request.getUserUuid());

        KsStoreUser ksStoreUser = ksStoreUserService.getOne(userWrapper);

        if (ksStoreUser == null) {
            return Result.buildResult(500, "用户不存在");
        }

        if (ksStoreUser.getKsSellerId() == null) {
            return Result.buildResult(500, "用户未授权");
        }

        MyLambdaQueryWrapper<KsOrders> wrapper = new MyLambdaQueryWrapper<>();

        wrapper.eq(KsOrders::getSellerId, ksStoreUser.getKsSellerId());

        if (request.getOid() != null) {
            wrapper.eq(KsOrders::getOid, request.getOid());
        }
        if (request.getPutLmStatus() != null) {
            wrapper.eq(KsOrders::getPutLmStatus, request.getPutLmStatus());
        }
        if (request.getSendStatus() != null) {
            wrapper.eq(KsOrders::getSendStatus, request.getSendStatus());
        }
        if (request.getStatus() != null) {
            wrapper.eq(KsOrders::getStatus, request.getStatus());
        }
        if (request.getSelfOrder() != null) {
            wrapper.eq(KsOrders::getSelfOrder, request.getSelfOrder());
        }
        if (request.getRefund() != null) {
            wrapper.eq(KsOrders::getRefund, request.getRefund());
        }
        if (StringUtils.isNotEmpty(request.getMobile())) {
            wrapper.like(KsOrders::getMobile, request.getMobile());
        }
        if (StringUtils.isNotEmpty(request.getLmRefundStatus())) {
            wrapper.like(KsOrders::getLmRefundStatus, request.getLmRefundStatus());
        }


        //  "relItemId":1613616754223,
        if (StringUtils.isNotEmpty(request.getRelItemId())) {
            wrapper.like(KsOrders::getOrderProductInfoList, ":" + request.getRelItemId() + ",");
        }

        if (StringUtils.isNotEmpty(request.getLmErrMsg())) {
            wrapper.like(KsOrders::getLmErrMsg, request.getLmErrMsg());
        }

        wrapper.orderByDesc(BaseEntity::getCreateDate);

        MyPage<KsOrders> lmSelfGoodsList = ksOrdersService.page(wrapper, request.getCurrentPage(), request.getPageSize(), true);

        return Result.buildResult(lmSelfGoodsList);

    }

    @ApiOperation(value = "条件大批量推送订单到LM")
    @RequestMapping(value = "batchPutOrderToLm", method = RequestMethod.POST)
    public Result<MyPage<KsOrders>> batchPutOrderToLm(@RequestBody GetMyKsOrdersRequest batchRequest) {
        try {
            return distributedLocker.lock("batchPutKsOrderToLm", () -> {
                System.out.println("执行方法！");
                // System.out.println(request.toString());
                MyLambdaQueryWrapper<KsStoreUser> userWrapper = new MyLambdaQueryWrapper<>();

                userWrapper.eq(KsStoreUser::getUuid, batchRequest.getUserUuid());

                KsStoreUser ksStoreUser = ksStoreUserService.getOne(userWrapper);

                if (ksStoreUser == null) {
                    return Result.buildResult(500, "用户不存在");
                }

                if (ksStoreUser.getKsSellerId() == null) {
                    return Result.buildResult(500, "用户未授权");
                }

                MyLambdaQueryWrapper<KsOrders> wrapper = new MyLambdaQueryWrapper<>();

                wrapper.eq(KsOrders::getSellerId, ksStoreUser.getKsSellerId());

                if (batchRequest.getOid() != null) {
                    wrapper.eq(KsOrders::getOid, batchRequest.getOid());
                }
                if (batchRequest.getPutLmStatus() != null) {
                    wrapper.eq(KsOrders::getPutLmStatus, batchRequest.getPutLmStatus());
                }
                if (batchRequest.getSendStatus() != null) {
                    wrapper.eq(KsOrders::getSendStatus, batchRequest.getSendStatus());
                }
                if (batchRequest.getStatus() != null) {
                    wrapper.eq(KsOrders::getStatus, batchRequest.getStatus());
                }
                if (batchRequest.getSelfOrder() != null) {
                    wrapper.eq(KsOrders::getSelfOrder, batchRequest.getSelfOrder());
                }
                if (batchRequest.getRefund() != null) {
                    wrapper.eq(KsOrders::getRefund, batchRequest.getRefund());
                }
                if (StringUtils.isNotEmpty(batchRequest.getMobile())) {
                    wrapper.like(KsOrders::getMobile, batchRequest.getMobile());
                }
                if (StringUtils.isNotEmpty(batchRequest.getRelItemId())) {
                    wrapper.like(KsOrders::getOrderProductInfoList, ":" + batchRequest.getRelItemId() + ",");
                }

                if (StringUtils.isNotEmpty(batchRequest.getLmErrMsg())) {
                    wrapper.like(KsOrders::getLmErrMsg, batchRequest.getLmErrMsg());
                }


                int page = 1;


                List<Long> fileSelfOrder = new ArrayList<>();
                List<Long> PutLmStatus = new ArrayList<>();
                List<Long> getStatus = new ArrayList<>();
                List<String> failOrder = new ArrayList<>();
                try {
                    while (true) {

                        MyPage<KsOrders> myPage = ksOrdersService.page(wrapper, 1, 100, false);

                        System.out.println("总数：" + myPage.getTotal());

                        //    System.out.println("总数：" + JSON.toJSONString(myPage.getRecords()));

                        List<KsOrders> ordersList = myPage.getRecords();

                        ordersList.forEach(ksOrders -> {

                            if (ksOrders.getSelfOrder() != 1) {
                                fileSelfOrder.add(ksOrders.getOid());
                            }
                            if (ksOrders.getPutLmStatus() != 0 && ksOrders.getPutLmStatus() != 2) {
                                PutLmStatus.add(ksOrders.getOid());
                            }
                            if (ksOrders.getStatus() != 30) {
                                getStatus.add(ksOrders.getOid());
                            }

                        });
                        if (fileSelfOrder.size() > 0) {
                            return Result.buildResult(500, "订单不为平台推送商品订单 单号如下：" + JSON.toJSONString(fileSelfOrder));
                        }
                        if (PutLmStatus.size() > 0) {
                            return Result.buildResult(500, "订单不为未推送订单或者推送失败订单 单号如下：" + JSON.toJSONString(fileSelfOrder));
                        }
                        if (getStatus.size() > 0) {
                            return Result.buildResult(500, "订单不为已支付未发货订单 单号如下：" + JSON.toJSONString(fileSelfOrder));
                        }


                        ordersList.forEach(ksOrders -> {
                            List<KsOrdersGoodsVO> ksOrdersGoodsVOList = JSON.parseArray(ksOrders.getOrderProductInfoList(), KsOrdersGoodsVO.class);

//[{"buyerId":0,"createTime":1612605117278,"discountFee":0,"id":8283462433580,"itemId":943491185290,"itemLinkUrl":"https://app.kwaixiaodian.com/merchant/shop/detail?id=943491185290&hyId=kwaishop&layoutType=4","itemPicUrl":"https://ali-ec.static.yximgs.com/ufile/adsocial/87243885-9d23-45e8-bd5d-d15dac7df6c0.jpg","itemTitle":"【瑜大直播】艺品赞红豆薏米茶150g*1袋","itemType":1,"num":1,"oid":2103700006986580,"originalPrice":990,"price":990,"refundId":2103700007004580,"refundList":[{"refundId":2103700007004580,"refundStatus":10}],"refundStatus":10,"relItemId":1612577579226,"relSkuId":0,"skuDesc":"红豆薏米茶","skuId":943491186290,"updateTime":1612605117278}]

                            if (ksOrdersGoodsVOList.size() > 0) {

                                KsOrdersGoodsVO ksOrdersGoods = ksOrdersGoodsVOList.get(0);

                                MyLambdaQueryWrapper<LmSelfGoods> selfGoodsWrapper = new MyLambdaQueryWrapper<>();

                                selfGoodsWrapper.eq(LmSelfGoods::getRelItemId, ksOrdersGoods.getRelItemId());

                                LmSelfGoods lmSelfGoods = lmSelfGoodsService.getOne(selfGoodsWrapper);

                                if (lmSelfGoods != null) {
                                    //    if(ksOrders.getStatus()==30){
                                    CreateOrderV2Request request = new CreateOrderV2Request();
                                    CreateOrderV2Request.ItemList itemList = new CreateOrderV2Request.ItemList();
                                    DeliveryAddress deliveryAddress = new DeliveryAddress();
                                    request.setBizId(LmConfig.LZ_BIZ_ID);
                                    request.setAccountType("ANONY");
                                    request.setThirdPartyUserId(ksOrders.getSellerId() + "");
                                    request.setBizUid(request.getThirdPartyUserId());

                                    List<CreateOrderV2Request.ItemList> itemLists = new ArrayList<>();

                                    request.setOutTradeId(ksOrders.getOid() + "");

                                    itemList.setLmItemId(lmSelfGoods.getLmItemId() + "");
                                    itemList.setQuantity((int) ksOrdersGoods.getNum());
                                    if (ksOrdersGoods.getRelSkuId() != 0) {
                                        itemList.setSkuId(ksOrdersGoods.getRelSkuId());
                                    } else {
                                        if (ksOrdersGoods.getSkuNick() != null) {
                                            itemList.setSkuId(Long.valueOf(ksOrdersGoods.getSkuNick()));
                                        }
                                    }


                                    KsOrdersAddress ksOrdersAddress = JSONObject.parseObject(ksOrders.getAddress(), KsOrdersAddress.class);

                                    /**
                                     * 设置地址
                                     */
                                    deliveryAddress.setFullName(ksOrdersAddress.getConsignee());
                                    deliveryAddress.setMobile(ksOrdersAddress.getMobile());
                                    //  deliveryAddress.setAddressDetail(ksOrdersAddress.getProvince() + ksOrdersAddress.getCity() + ksOrdersAddress.getDistrict() + ksOrdersAddress.getAddress());
                                    deliveryAddress.setAddressDetail(ksOrdersAddress.getAddress());

                                    MyLambdaQueryWrapper<LmAddress> provinceWrapper = new MyLambdaQueryWrapper<>();

                                    provinceWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince());

                                    provinceWrapper.eq(LmAddress::getParentId, 1);

                                    LmAddress province = lmAddressService.getOne(provinceWrapper);

                                    if (province == null) {
                                        MyLambdaQueryWrapper<LmAddress> provinceWrapper2 = new MyLambdaQueryWrapper<>();

                                        provinceWrapper2.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince().replace("市", ""));

                                        provinceWrapper2.eq(LmAddress::getParentId, 1);
                                        province = lmAddressService.getOne(provinceWrapper2);
                                    }

                                    if (province != null) {
                                        MyLambdaQueryWrapper<LmAddress> cityWrapper = new MyLambdaQueryWrapper<>();

                                        cityWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getCity());

                                        cityWrapper.eq(LmAddress::getParentId, province.getDivisionCode());

                                        LmAddress city = lmAddressService.getOne(cityWrapper);

                                        boolean jump = false;

                                        if (city == null) {
                                            if (ksOrdersAddress.getCity().equals("市辖区") || ksOrdersAddress.getCity().equals("县")) {

                                                MyLambdaQueryWrapper<LmAddress> cityWrapper1 = new MyLambdaQueryWrapper<>();

                                                cityWrapper1.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince());

                                                cityWrapper1.eq(LmAddress::getParentId, province.getDivisionCode());

                                                city = lmAddressService.getOne(cityWrapper1);
                                            } else {
                                                if (ksOrdersAddress.getCity().equals("自治区直辖县级行政区划") || ksOrdersAddress.getCity().equals("省直辖县级行政区划")) {
                                                    jump = true;
                                                }
                                            }
                                        }
                                        if (city == null && !jump) {
                                            System.out.println(ksOrders.getAddress());
                                            System.out.println("系统不存在" + ksOrdersAddress.getProvince() + "省下的：" + ksOrdersAddress.getCity());
                                        } else {
                                            LmAddress dest;
                                            if (jump) {
                                                MyLambdaQueryWrapper<LmAddress> destWrapper = new MyLambdaQueryWrapper<>();

                                                destWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getDistrict());

                                                destWrapper.eq(LmAddress::getParentId, province.getDivisionCode());

                                                dest = lmAddressService.getOne(destWrapper);
                                            } else {
                                                MyLambdaQueryWrapper<LmAddress> destWrapper = new MyLambdaQueryWrapper<>();

                                                destWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getDistrict());

                                                destWrapper.eq(LmAddress::getParentId, city.getDivisionCode());

                                                dest = lmAddressService.getOne(destWrapper);
                                            }

                                            if (dest == null) {

                                                if (jump) {
                                                    MyLambdaQueryWrapper<LmAddress> destWrapper1 = new MyLambdaQueryWrapper<>();

                                                    destWrapper1.like(LmAddress::getDivisionName, "其它区");

                                                    destWrapper1.eq(LmAddress::getParentId, province.getDivisionCode());

                                                    dest = lmAddressService.getOne(destWrapper1);
                                                } else {
                                                    MyLambdaQueryWrapper<LmAddress> destWrapper1 = new MyLambdaQueryWrapper<>();

                                                    destWrapper1.like(LmAddress::getDivisionName, "其它区");

                                                    destWrapper1.eq(LmAddress::getParentId, city.getDivisionCode());

                                                    dest = lmAddressService.getOne(destWrapper1);
                                                }

                                                if (dest == null) {
                                                    System.out.println("系统不存在" + ksOrdersAddress.getProvince() + "省下：" + ksOrdersAddress.getCity() + "市的区：" + ksOrdersAddress.getDistrict());
                                                }


                                            }

                                            if (dest != null) {

                                                deliveryAddress.setDivisionCode(dest.getDivisionCode() + "");

                                                List<Map<String, String>> table = AddressResolutionUtil.addressResolution(ksOrdersAddress.getAddress());

                                                if (table.size() > 0) {

                                                    String townName = table.get(0).get("town");

                                                    if (!StringUtils.isEmpty(townName)) {

                                                        //    System.out.println("街道名字："+townName);

                                                        MyLambdaQueryWrapper<LmAddress> townWrapper = new MyLambdaQueryWrapper<>();

                                                        townWrapper.like(LmAddress::getDivisionName, townName);

                                                        townWrapper.eq(LmAddress::getParentId, dest.getDivisionCode());

                                                        LmAddress town = lmAddressService.getOne(townWrapper);

                                                        if (town != null) {
                                                            //    System.out.println("街道："+town.toString());
                                                            deliveryAddress.setTownDivisionCode(town.getDivisionCode() + "");
                                                        }
                                                    }
                                                }

                                                itemLists.add(itemList);

                                                request.setItemLists(itemLists);

                                                //    System.out.println("地址详细："+JSON.toJSONString(deliveryAddress));

                                                request.setDeliveryAddress(JSON.toJSONString(deliveryAddress));

                                                try {
                                                    //    System.out.println("请求内容："+JSON.toJSONString(request));
                                                    //创建订单
                                                    CreateOrderV2Response resp = client.getAcsResponse(request);
                                                    System.out.println("正在推送");
                                                    System.out.println("报文内容：" + JSON.toJSONString(resp.getMessage()));


                                                    if (resp.getCode().equals("SUCCESS")) {

                                                        ksOrders.setLmOrderId(resp.getModel().getLmOrderList().get(0).getLmOrderId());
                                                        ksOrders.setTbOrderId(resp.getModel().getOrderIds().get(0));

                                                        EnableOrderResponse enableOrderResponse = enableOrder(request.getOutTradeId(), resp.getModel().getLmOrderList().get(0).getLmOrderId(), ksOrders.getSellerId() + "");

                                                        if (enableOrderResponse.getCode().equals("SUCCESS")) {
                                                            ksOrders.setPutLmStatus(1);
                                                        } else {
                                                            ksOrders.setPutLmStatus(2);
                                                            failOrder.add(ksOrders.getOid() + "");
                                                        }

                                                        ksOrders.setLmErrMsg(JSON.toJSONString(enableOrderResponse));
                                                    } else {
                                                        //  failOrder.add(ksOrders.getOid() + "");
                                                        if (resp.getCode().equals("CALL_TRADE_SRVICE_FAIL")) {
                                                            System.out.println("跳过保存");
                                                        } else if (resp.getCode().equals("CREATE_ORDER_REPEATE")) {
                                                            if (StringUtils.isNotEmpty(ksOrders.getLmOrderId())) {
                                                                EnableOrderResponse enableOrderResponse = enableOrder(request.getOutTradeId(), ksOrders.getLmOrderId(), ksOrders.getSellerId() + "");
                                                                if (enableOrderResponse.getCode().equals("SUCCESS")) {
                                                                    ksOrders.setPutLmStatus(1);
                                                                } else {
                                                                    ksOrders.setPutLmStatus(2);
                                                                    failOrder.add(ksOrders.getOid() + "");
                                                                }
                                                            } else {
                                                                ksOrders.setPutLmStatus(2);
                                                                ksOrders.setLmErrMsg(JSON.toJSONString(resp));
                                                            }
                                                        }
                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                                ksOrdersService.updateById(ksOrders);
                                            } else {
                                                ksOrders.setPutLmStatus(2);
                                                ksOrders.setLmErrMsg("{\"code\":\"NO_ADDRESS\",\"logsId\":\"\",\"message\":\"无对应地址\",\"model\":{\"lmOrderList\":[],\"orderIds\":[],\"payTradeIds\":[],\"redirectUrl\":\"\"},\"requestId\":\"120F7222-4C88-4FC5-BD7E-3A9B3557F32D\",\"subCode\":\"\",\"subMessage\":\"\",\"success\":true}");
                                                ksOrdersService.updateById(ksOrders);
                                            }
                                        }
                                    } else {
                                        System.out.println("系统不存在省份：" + ksOrdersAddress.getProvince());
                                    }
                                }
                            }
                        });

                        if (myPage.getRecords().size() < 100) {
                            break;
                        }
                        page += 1;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (failOrder.size() > 0) {
                    return Result.buildResult(500, "推送失败的订单订单：" + JSON.toJSONString(failOrder));
                }

                return Result.buildResult();

            }, 100, 2);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.buildResult(500, "上批订单还未处理完，请稍后再试！");
        }
    }

    @ApiOperation(value = "小批量推送订单到LM")
    @RequestMapping(value = "putOrderToLm", method = RequestMethod.POST)
    public Result putOrderToLm(@RequestBody List<IdsRequest> requests) {

        //       System.out.println(requests);

        List<Integer> ids = requests.stream().map(IdsRequest::getId).collect(Collectors.toList());

        MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.in(BaseEntity::getId, ids);

        List<KsOrders> ordersList = ksOrdersService.list(queryWrapper);


        List<Long> fileSelfOrder = new ArrayList<>();
        List<Long> PutLmStatus = new ArrayList<>();
        List<Long> getStatus = new ArrayList<>();


        ordersList.forEach(ksOrders -> {

            if (ksOrders.getSelfOrder() != 1) {
                fileSelfOrder.add(ksOrders.getOid());
            }
            if (ksOrders.getPutLmStatus() != 0 && ksOrders.getPutLmStatus() != 2) {
                PutLmStatus.add(ksOrders.getOid());
            }
            if (ksOrders.getStatus() != 30) {
                getStatus.add(ksOrders.getOid());
            }

        });
        if (fileSelfOrder.size() > 0) {
            return Result.buildResult(500, "订单不为平台推送商品订单 单号如下：" + JSON.toJSONString(fileSelfOrder));
        }
        if (PutLmStatus.size() > 0) {
            return Result.buildResult(500, "订单不为未推送订单或者推送失败订单 单号如下：" + JSON.toJSONString(PutLmStatus));
        }
        if (getStatus.size() > 0) {
            return Result.buildResult(500, "订单已支付未发货订单 单号如下：" + JSON.toJSONString(getStatus));
        }


//        MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();
//
//        queryWrapper.in(KsOrders::getSelfOrder, 1);//平台商品的订单 0未确定 1是 2不是
//
//        queryWrapper.eq(KsOrders::getPutLmStatus, 0);//推送lm状态 0未推送 1已推送 2推送失败
//
//        queryWrapper.eq(KsOrders::getStatus, 30);//订单状态：[0, \"未知状态\"], [10, \"待付款\"], [30, \"已付款\"], [40, \"已发货\"], [50, \"已签收\"], [70, \"订单成功\"], [80, \"订单失败\"]
//
//
//        List<KsOrders> ksOrdersList = ksOrdersService.list(queryWrapper);

        List<String> failOrder = new ArrayList<>();

        ordersList.forEach(ksOrders -> {
            List<KsOrdersGoodsVO> ksOrdersGoodsVOList = JSON.parseArray(ksOrders.getOrderProductInfoList(), KsOrdersGoodsVO.class);

//[{"buyerId":0,"createTime":1612605117278,"discountFee":0,"id":8283462433580,"itemId":943491185290,"itemLinkUrl":"https://app.kwaixiaodian.com/merchant/shop/detail?id=943491185290&hyId=kwaishop&layoutType=4","itemPicUrl":"https://ali-ec.static.yximgs.com/ufile/adsocial/87243885-9d23-45e8-bd5d-d15dac7df6c0.jpg","itemTitle":"【瑜大直播】艺品赞红豆薏米茶150g*1袋","itemType":1,"num":1,"oid":2103700006986580,"originalPrice":990,"price":990,"refundId":2103700007004580,"refundList":[{"refundId":2103700007004580,"refundStatus":10}],"refundStatus":10,"relItemId":1612577579226,"relSkuId":0,"skuDesc":"红豆薏米茶","skuId":943491186290,"updateTime":1612605117278}]

            if (ksOrdersGoodsVOList.size() > 0) {

                KsOrdersGoodsVO ksOrdersGoods = ksOrdersGoodsVOList.get(0);

                MyLambdaQueryWrapper<LmSelfGoods> selfGoodsWrapper = new MyLambdaQueryWrapper<>();

                selfGoodsWrapper.eq(LmSelfGoods::getRelItemId, ksOrdersGoods.getRelItemId());

                LmSelfGoods lmSelfGoods = lmSelfGoodsService.getOne(selfGoodsWrapper);

                if (lmSelfGoods != null) {
                    //    if(ksOrders.getStatus()==30){
                    CreateOrderV2Request request = new CreateOrderV2Request();
                    CreateOrderV2Request.ItemList itemList = new CreateOrderV2Request.ItemList();
                    DeliveryAddress deliveryAddress = new DeliveryAddress();
                    request.setBizId(LmConfig.LZ_BIZ_ID);
                    request.setAccountType("ANONY");
                    request.setThirdPartyUserId(ksOrders.getSellerId() + "");
                    request.setBizUid(request.getThirdPartyUserId());

                    List<CreateOrderV2Request.ItemList> itemLists = new ArrayList<>();

                    request.setOutTradeId(ksOrders.getOid() + "");

                    itemList.setLmItemId(lmSelfGoods.getLmItemId() + "");

                    itemList.setQuantity((int) ksOrdersGoods.getNum());

                    if (ksOrdersGoods.getRelSkuId() != 0) {
                        itemList.setSkuId(ksOrdersGoods.getRelSkuId());
                    } else {
                        if (ksOrdersGoods.getSkuNick() != null) {
                            itemList.setSkuId(Long.valueOf(ksOrdersGoods.getSkuNick()));
                        }
                    }


                    KsOrdersAddress ksOrdersAddress = JSONObject.parseObject(ksOrders.getAddress(), KsOrdersAddress.class);

                    /**
                     * 设置地址
                     */
                    deliveryAddress.setFullName(ksOrdersAddress.getConsignee());
                    deliveryAddress.setMobile(ksOrdersAddress.getMobile());
                    deliveryAddress.setAddressDetail(ksOrdersAddress.getAddress());
                    //   deliveryAddress.setAddressDetail(ksOrdersAddress.getProvince() + ksOrdersAddress.getCity() + ksOrdersAddress.getDistrict() + ksOrdersAddress.getAddress());

                    MyLambdaQueryWrapper<LmAddress> provinceWrapper = new MyLambdaQueryWrapper<>();

                    provinceWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince());

                    provinceWrapper.eq(LmAddress::getParentId, 1);

                    LmAddress province = lmAddressService.getOne(provinceWrapper);

                    if (province == null) {
                        MyLambdaQueryWrapper<LmAddress> provinceWrapper2 = new MyLambdaQueryWrapper<>();

                        provinceWrapper2.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince().replace("市", ""));

                        provinceWrapper2.eq(LmAddress::getParentId, 1);
                        province = lmAddressService.getOne(provinceWrapper2);
                    }

                    if (province != null) {
                        MyLambdaQueryWrapper<LmAddress> cityWrapper = new MyLambdaQueryWrapper<>();

                        cityWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getCity());

                        cityWrapper.eq(LmAddress::getParentId, province.getDivisionCode());

                        LmAddress city = lmAddressService.getOne(cityWrapper);

                        boolean jump = false;

                        if (city == null) {
                            if (ksOrdersAddress.getCity().equals("市辖区") || ksOrdersAddress.getCity().equals("县")) {

                                MyLambdaQueryWrapper<LmAddress> cityWrapper1 = new MyLambdaQueryWrapper<>();

                                cityWrapper1.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince());

                                cityWrapper1.eq(LmAddress::getParentId, province.getDivisionCode());

                                city = lmAddressService.getOne(cityWrapper1);
                            } else {
                                if (ksOrdersAddress.getCity().equals("自治区直辖县级行政区划") || ksOrdersAddress.getCity().equals("省直辖县级行政区划")) {
                                    jump = true;
                                }
                            }
                        }
                        if (city == null && !jump) {
                            System.out.println(ksOrders.getAddress());
                            System.out.println("系统不存在" + ksOrdersAddress.getProvince() + "省下的：" + ksOrdersAddress.getCity());
                        } else {
                            LmAddress dest;
                            if (jump) {
                                MyLambdaQueryWrapper<LmAddress> destWrapper = new MyLambdaQueryWrapper<>();

                                destWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getDistrict());

                                destWrapper.eq(LmAddress::getParentId, province.getDivisionCode());

                                dest = lmAddressService.getOne(destWrapper);
                            } else {
                                MyLambdaQueryWrapper<LmAddress> destWrapper = new MyLambdaQueryWrapper<>();

                                destWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getDistrict());

                                destWrapper.eq(LmAddress::getParentId, city.getDivisionCode());

                                dest = lmAddressService.getOne(destWrapper);
                            }

                            if (dest == null) {

                                if (jump) {
                                    MyLambdaQueryWrapper<LmAddress> destWrapper1 = new MyLambdaQueryWrapper<>();

                                    destWrapper1.like(LmAddress::getDivisionName, "其它区");

                                    destWrapper1.eq(LmAddress::getParentId, province.getDivisionCode());

                                    dest = lmAddressService.getOne(destWrapper1);
                                } else {
                                    MyLambdaQueryWrapper<LmAddress> destWrapper1 = new MyLambdaQueryWrapper<>();

                                    destWrapper1.like(LmAddress::getDivisionName, "其它区");

                                    destWrapper1.eq(LmAddress::getParentId, city.getDivisionCode());

                                    dest = lmAddressService.getOne(destWrapper1);
                                }

                                if (dest == null) {
                                    System.out.println("系统不存在" + ksOrdersAddress.getProvince() + "省下：" + ksOrdersAddress.getCity() + "市的区：" + ksOrdersAddress.getDistrict());
                                }


                            }

                            if (dest != null) {

                                deliveryAddress.setDivisionCode(dest.getDivisionCode() + "");

                                List<Map<String, String>> table = AddressResolutionUtil.addressResolution(ksOrdersAddress.getAddress());

                                if (table.size() > 0) {

                                    String townName = table.get(0).get("town");

                                    if (!StringUtils.isEmpty(townName)) {

                                        //    System.out.println("街道名字："+townName);

                                        MyLambdaQueryWrapper<LmAddress> townWrapper = new MyLambdaQueryWrapper<>();

                                        townWrapper.like(LmAddress::getDivisionName, townName);

                                        townWrapper.eq(LmAddress::getParentId, dest.getDivisionCode());

                                        LmAddress town = lmAddressService.getOne(townWrapper);

                                        if (town != null) {
                                            //    System.out.println("街道："+town.toString());
                                            deliveryAddress.setTownDivisionCode(town.getDivisionCode() + "");
                                        }
                                    }
                                }

                                itemLists.add(itemList);

                                request.setItemLists(itemLists);

                                //    System.out.println("地址详细："+JSON.toJSONString(deliveryAddress));

                                request.setDeliveryAddress(JSON.toJSONString(deliveryAddress));

                                try {
                                    //    System.out.println("请求内容："+JSON.toJSONString(request));
                                    //创建订单
                                    CreateOrderV2Response resp = client.getAcsResponse(request);
                                    System.out.println("正在推送");
                                    System.out.println("报文内容：" + JSON.toJSONString(resp.getMessage()));


                                    if (resp.getCode().equals("SUCCESS")) {

                                        ksOrders.setLmOrderId(resp.getModel().getLmOrderList().get(0).getLmOrderId());
                                        ksOrders.setTbOrderId(resp.getModel().getOrderIds().get(0));

                                        EnableOrderResponse enableOrderResponse = enableOrder(request.getOutTradeId(), resp.getModel().getLmOrderList().get(0).getLmOrderId(), ksOrders.getSellerId() + "");

                                        if (enableOrderResponse.getCode().equals("SUCCESS")) {
                                            ksOrders.setPutLmStatus(1);
                                        } else {
                                            ksOrders.setPutLmStatus(2);
                                            failOrder.add(ksOrders.getOid() + "");
                                        }

                                        ksOrders.setLmErrMsg(JSON.toJSONString(enableOrderResponse));
                                    } else {
                                        //   failOrder.add(ksOrders.getOid() + "");
                                        if (resp.getCode().equals("CALL_TRADE_SRVICE_FAIL")) {
                                            System.out.println("跳过保存");
                                        } else if (resp.getCode().equals("CREATE_ORDER_REPEATE")) {
                                            if (StringUtils.isNotEmpty(ksOrders.getLmOrderId())) {
                                                EnableOrderResponse enableOrderResponse = enableOrder(request.getOutTradeId(), ksOrders.getLmOrderId(), ksOrders.getSellerId() + "");
                                                if (enableOrderResponse.getCode().equals("SUCCESS")) {
                                                    ksOrders.setPutLmStatus(1);
                                                } else {
                                                    ksOrders.setPutLmStatus(2);
                                                    failOrder.add(ksOrders.getOid() + "");
                                                }
                                                System.out.println("跳过保存");
                                            } else {
                                                ksOrders.setPutLmStatus(2);
                                                ksOrders.setLmErrMsg(JSON.toJSONString(resp));
                                            }
                                        } else {
                                            ksOrders.setPutLmStatus(2);
                                            ksOrders.setLmErrMsg(JSON.toJSONString(resp));
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                ksOrdersService.updateById(ksOrders);
                            } else {
                                ksOrders.setPutLmStatus(2);
                                ksOrders.setLmErrMsg("{\"code\":\"NO_ADDRESS\",\"logsId\":\"\",\"message\":\"无对应地址\",\"model\":{\"lmOrderList\":[],\"orderIds\":[],\"payTradeIds\":[],\"redirectUrl\":\"\"},\"requestId\":\"120F7222-4C88-4FC5-BD7E-3A9B3557F32D\",\"subCode\":\"\",\"subMessage\":\"\",\"success\":true}");
                                ksOrdersService.updateById(ksOrders);
                            }
                        }
                    } else {
                        System.out.println("系统不存在省份：" + ksOrdersAddress.getProvince());
                    }
                }
            }
        });
        if (failOrder.size() > 0) {
            return Result.buildResult(500, "推送失败的订单订单：" + JSON.toJSONString(failOrder));
        }
        return Result.buildResult();
    }

    @ApiOperation(value = "单个订单向LM发起退款前渲染", notes = "注意：Lm订单“未发货”只能申请“仅退款(BizClaimType=1)”，订单“已发货”只能申请货物状态为“未收到货 (GoodsStatus=1)”或“已收到货(GoodsStatus=2)”")
    @RequestMapping(value = "beforeRefundOrderToLm", method = RequestMethod.POST)
    public Result<InitApplyRefundResponse> beforeRefundOrderToLm(@RequestBody BeforeRefundOrderToLmRequest requests) throws ClientException {

        Set<Long> faildIds = new HashSet<>();

        // List<Integer> ids = requests.getIds();

        MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());

        KsOrders ksOrders = ksOrdersService.getOne(queryWrapper);


        InitApplyRefundRequest request = new InitApplyRefundRequest();
        request.setBizId(LmConfig.LZ_BIZ_ID);
        request.setAccountType("ANONY");
        request.setThirdPartyUserId(ksOrders.getSellerId() + "");
        request.setBizUid(request.getThirdPartyUserId());

        //注意：订单“未发货”只能申请“仅退款(BizClaimType=1)”，订单“已发货”只能申请货物状态为“未收到货 (GoodsStatus=1)”或“已收到货(GoodsStatus=2)”

        //发起退款的⼦订 单，可在查询订单 详情接⼝中获取
        request.setSubLmOrderId(ksOrders.getLmOrderId());
        //4: 未发货, 6: 已 发货, 1: 未收到货, 2: 已收到货, 3: 已寄回, 5: 卖家 确认收货
        request.setGoodsStatus(requests.getGoodsStatus());
        //1 仅退款，3 退货 退款
        request.setBizClaimType(requests.getBizClaimType());

        InitApplyRefundResponse resp = client.getAcsResponse(request);

        return Result.buildResult(resp);
    }

    @ApiOperation(value = "单个订单向LM发起退款")
    @RequestMapping(value = "RefundOrderToLm", method = RequestMethod.POST)
    public Result RefundOrderToLm(@RequestBody RefundOrderToLmRequest requests) {

        //  System.out.println(JSON.toJSONString(requests));

        Set<Long> faildIds = new HashSet<>();

        // List<Integer> ids = requests.getIds();

        MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());
        KsOrders ksOrders = ksOrdersService.getOne(queryWrapper);

        if (ksOrders == null) {
            return Result.buildResult(500, "订单不存在");
        }

        if (ksOrders.getRefund() != 1) {//是否申请退款 0未申请 1已申请
            return Result.buildResult(500, "端订单未申请退款");
        }

//        if (ksOrders.getLmRefundStatus() != 0 && ksOrders.getLmRefundStatus() != 4) {//lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败
//            return Result.buildResult(500, "lm退款申请状态 不为 0未申请 或者  4申请失败");
//        }

        try {
            ApplyRefundRequest applyRefundRequest = new ApplyRefundRequest();
            applyRefundRequest.setBizId(LmConfig.LZ_BIZ_ID);
            applyRefundRequest.setAccountType("ANONY");
            applyRefundRequest.setThirdPartyUserId(ksOrders.getSellerId() + "");
            applyRefundRequest.setBizUid(applyRefundRequest.getThirdPartyUserId());
            applyRefundRequest.setBizClaimType(requests.getBizClaimType());
            applyRefundRequest.setGoodsStatus(requests.getGoodsStatus());
            applyRefundRequest.setSubLmOrderId(ksOrders.getLmOrderId());

            BigDecimal price = new BigDecimal(requests.getApplyRefundFee()).multiply(BigDecimal.valueOf(100));


            applyRefundRequest.setApplyRefundFee(price.longValue());
            applyRefundRequest.setApplyReasonTextId(requests.getReasonTextId());

            if (!StringUtils.isEmpty(requests.getLeaveMessage())) {
                applyRefundRequest.setLeaveMessage(requests.getLeaveMessage());
            }

            if (requests.getPicRequestList().size() > 0) {
                List<ApplyRefundRequest.LeavePictureList> leavePictureLists = new ArrayList<>();
                requests.getPicRequestList().forEach(refundOrderToLmPicRequest -> {
                    ApplyRefundRequest.LeavePictureList picture = new ApplyRefundRequest.LeavePictureList();
                    picture.setPicture(refundOrderToLmPicRequest.getPicture());
                    picture.setDesc(refundOrderToLmPicRequest.getPicture());
                    leavePictureLists.add(picture);
                });
                applyRefundRequest.setLeavePictureLists(leavePictureLists);
            }

            ApplyRefundResponse applyRefundResponse = client.getAcsResponse(applyRefundRequest);

            ksOrders.setLmRefundMsg(JSON.toJSONString(applyRefundResponse));

            // System.out.println(JSON.toJSONString(applyRefundResponse));

            if (applyRefundResponse.getCode().equals("SUCCESS")) {
                //lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败
                ksOrders.setLmRefundStatus(1);
            } else {
                faildIds.add(ksOrders.getOid());
                ksOrders.setLmRefundStatus(4);
                return Result.buildResult(500, "LM发起退款失败 原因如下：" + applyRefundResponse.getMessage());
            }
            ksOrdersService.updateById(ksOrders);

        } catch (ClientException e) {
            faildIds.add(ksOrders.getOid());
            e.printStackTrace();
        }
        if (faildIds.size() > 0) {
            return Result.buildResult(500, "退款失败订单如下：" + JSON.toJSONString(faildIds));
        }
        return Result.buildResult();
    }

    @ApiOperation(value = "LM查询退款申请详情")
    @RequestMapping(value = "queryRefundApplicationDetail", method = RequestMethod.POST)
    public Result<RefundApplicationDetailResponse> queryRefundApplicationDetail(@RequestBody LmQueryRefundApplicationDetailRequest requests) {

        MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());
        KsOrders ksOrders = ksOrdersService.getOne(queryWrapper);

        if (ksOrders == null) {
            return Result.buildResult(500, "订单不存在");
        }

        if (ksOrders.getLmRefundStatus() == 0) {//lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败
            return Result.buildResult(500, "订单未向LM申请退款");
        }

        try {
            QueryRefundApplicationDetailRequest applyRefundRequest = new QueryRefundApplicationDetailRequest();
            applyRefundRequest.setBizId(LmConfig.LZ_BIZ_ID);
            applyRefundRequest.setAccountType("ANONY");
            applyRefundRequest.setThirdPartyUserId(ksOrders.getSellerId() + "");
            applyRefundRequest.setBizUid(applyRefundRequest.getThirdPartyUserId());
            applyRefundRequest.setSubLmOrderId(ksOrders.getLmOrderId());

            QueryRefundApplicationDetailResponse applyRefundResponse = client.getAcsResponse(applyRefundRequest);

            System.out.println(JSON.toJSONString(applyRefundResponse));

            RefundApplicationDetailResponse response = JSON.toJavaObject(JSON.parseObject(JSON.toJSONString(applyRefundResponse)), RefundApplicationDetailResponse.class);

            System.out.println(JSON.toJSONString(response));

            return Result.buildResult(response);

        } catch (ClientException e) {

            e.printStackTrace();
        }
        return Result.buildResult();
    }

    @ApiOperation(value = "单个订单向LM发起取消退款")
    @RequestMapping(value = "lmCancelRefund", method = RequestMethod.POST)
    public Result lmCancelRefund(@RequestBody LmCancelRequest requests) {

        Set<Long> faildIds = new HashSet<>();

        // List<Integer> ids = requests.getIds();

        MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());
        KsOrders ksOrders = ksOrdersService.getOne(queryWrapper);

        if (ksOrders == null) {
            return Result.buildResult(500, "订单不存在");
        }

        if (ksOrders.getLmRefundStatus() != 1) {//lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败
            return Result.buildResult(500, "lm退款申请不为状态 1已申请");
        }

        try {
            CancelRefundRequest applyRefundRequest = new CancelRefundRequest();
            applyRefundRequest.setBizId(LmConfig.LZ_BIZ_ID);
            applyRefundRequest.setAccountType("ANONY");
            applyRefundRequest.setThirdPartyUserId(ksOrders.getSellerId() + "");
            applyRefundRequest.setBizUid(applyRefundRequest.getThirdPartyUserId());
            applyRefundRequest.setSubLmOrderId(ksOrders.getLmOrderId());
            applyRefundRequest.setDisputeId(requests.getDisputeId());

            CancelRefundResponse applyRefundResponse = client.getAcsResponse(applyRefundRequest);

            ksOrders.setLmRefundMsg(JSON.toJSONString(applyRefundResponse));

            if (applyRefundResponse.getCode().equals("SUCCESS")) {
                //lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败 5已取消 6已提交物流 7提交物流失败 8取消退款失败
                ksOrders.setLmRefundStatus(5);
            } else {
                faildIds.add(ksOrders.getOid());
                ksOrders.setLmRefundStatus(8);
            }
            ksOrdersService.updateById(ksOrders);

        } catch (ClientException e) {
            faildIds.add(ksOrders.getOid());
            e.printStackTrace();
        }
        if (faildIds.size() > 0) {
            return Result.buildResult(500, "取消退款失败订单如下：" + JSON.toJSONString(faildIds));
        }
        return Result.buildResult();
    }

    @ApiOperation(value = "Lm提交退货物流信息接⼝")
    @RequestMapping(value = "lmSubmitReturnGoodLogistics", method = RequestMethod.POST)
    public Result lmSubmitReturnGoodLogistics(@RequestBody LmSubmitReturnGoodLogisticsRequest requests) {

        Set<Long> faildIds = new HashSet<>();

        // List<Integer> ids = requests.getIds();

        MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());
        KsOrders ksOrders = ksOrdersService.getOne(queryWrapper);

        if (ksOrders == null) {
            return Result.buildResult(500, "订单不存在");
        }

//        if (ksOrders.getLmRefundStatus() != 1) {//lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败
//            return Result.buildResult(500, "lm退款申请不为状态 1已申请");
//        }

        try {
            SubmitReturnGoodLogisticsRequest applyRefundRequest = new SubmitReturnGoodLogisticsRequest();
            applyRefundRequest.setBizId(LmConfig.LZ_BIZ_ID);
            applyRefundRequest.setAccountType("ANONY");
            applyRefundRequest.setThirdPartyUserId(ksOrders.getSellerId() + "");
            applyRefundRequest.setBizUid(applyRefundRequest.getThirdPartyUserId());
            applyRefundRequest.setSubLmOrderId(requests.getSubLmOrderId());
            applyRefundRequest.setDisputeId(Long.valueOf(requests.getDisputeId()));
            applyRefundRequest.setLogisticsNo(requests.getLogisticsNo());
            applyRefundRequest.setCpCode(requests.getCpCode());

            SubmitReturnGoodLogisticsResponse applyRefundResponse = client.getAcsResponse(applyRefundRequest);

            ksOrders.setLmRefundMsg(JSON.toJSONString(applyRefundResponse));

            if (applyRefundResponse.getCode().equals("SUCCESS")) {
                //lm退款状态 0未申请 1已申请 2已退款 3拒绝退款 4申请失败 5已取消 6已提交物流 7提交物流失败 8取消退款失败
                ksOrders.setLmRefundStatus(6);
            } else {
                faildIds.add(ksOrders.getOid());
                ksOrders.setLmRefundStatus(7);
            }
            ksOrdersService.updateById(ksOrders);

        } catch (ClientException e) {
            faildIds.add(ksOrders.getOid());
            e.printStackTrace();
            return Result.buildResult(500, e.getMessage());
        }
        if (faildIds.size() > 0) {
            return Result.buildResult(500, "提交退货物流失败订单如下：" + JSON.toJSONString(faildIds));
        }
        return Result.buildResult();
    }

    @ApiOperation(value = "订单同意退款")
    @RequestMapping(value = "refundApproveKs", method = RequestMethod.POST)
    public Result refundApproveKs(@RequestBody KsOrderRefundApproveRequest requests) {
        KsStoreUser ksStoreUser = ksConfig.getKsStoreUserConfig();

        KsOauth ksOauth = ksStoreUser.getKsOauth();

        if (ksOauth == null) {
            return Result.buildResult(500, "账号未授权");
        }

        MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());

        KsOrders ksOrders = ksOrdersService.getOne(queryWrapper);

        if (ksOrders == null) {
            return Result.buildResult(500, "订单不存在");
        }

        if (ksOrders.getKsRefundId() == null) {
            return Result.buildResult(500, "订单退款信息未更新，请稍后再试！");
        }

        KsMerchantRefundApproveRequest refundApproveRequest = new KsMerchantRefundApproveRequest();

        CopyUtils.copyProperties(requests, refundApproveRequest);
        refundApproveRequest.setAccessToken(ksOauth.getAccessToken());
        refundApproveRequest.setRefundId(ksOrders.getKsRefundId());

        AccessTokenKsMerchantClient tokenKsMerchantClient
                = new AccessTokenKsMerchantClient("", KsConfigInfo.appKey, KsConfigInfo.signSecret);

        try {
            KsMerchantRefundApproveResponse response = tokenKsMerchantClient.execute(refundApproveRequest);

            if (response.getResult() != 1) {
                return Result.buildResult(500, response.getErrorMsg());
            } else {
                return Result.buildResult();
            }
        } catch (KsMerchantApiException e) {
            e.printStackTrace();
        }
        return Result.buildResult(500, "未知错误");
    }

    @ApiOperation(value = "查看售后单详情")
    @RequestMapping(value = "refundOrdersDetail", method = RequestMethod.POST)
    public Result refundOrdersDetail(@RequestBody RefundOrdersDetailRequest requests) throws KsMerchantApiException {

        KsStoreUser ksStoreUser = ksConfig.getKsStoreUserConfig();

        KsOauth ksOauth = ksStoreUser.getKsOauth();

        if (ksOauth == null) {
            return Result.buildResult(500, "账号未授权");
        }

        KsMerchantRefundDetailRequest orderListRequest = new KsMerchantRefundDetailRequest();
        orderListRequest.setAccessToken(ksOauth.getAccessToken());
        orderListRequest.setRefundId(requests.getKsRefundId());

        AccessTokenKsMerchantClient tokenKsMerchantClient
                = new AccessTokenKsMerchantClient("", KsConfigInfo.appKey, KsConfigInfo.signSecret);

        KsMerchantRefundDetailResponse response = tokenKsMerchantClient.execute(orderListRequest);

        return Result.buildResult(response);

    }

    @ApiOperation(value = "获得快递代码")
    @RequestMapping(value = "getCpCode", method = RequestMethod.POST)
    public Result getCpCode() {

        String arr = "{ " +
                "\"STO\": \"申通快递\", " +
                "\"HTKY\": \"百世快递\", " +
                "\"DBKD\": \"德邦快递\"," +
                "\"POSTB\": \"邮政快递包裹\"," +
                "\"EYB\": \"EMS经济快递\", " +
                "\"GTO\": \"国通快递\", " +
                "\"QFKD\": \"全峰快递\", " +
                " \"ZJS\": \"宅急送\", " +
                " \"FAST\": \"快捷快递\", " +
                " \"EMS\": \"EMS标准\", " +
                " \"SF\": \"顺丰速运\", " +
                " \"UC\": \"优速快递\", " +
                " \"100004928\": \"如⻛达\", " +
                " \"5000000007756\": \"中国邮政国内标快\", " +
                " \"BESTQJT\": \"百世快运\", " +
                " \"ZTO\": \"中通快递\", " +
                " \"TTKDEX\": \"天天快递\", " +
                " \"YTO\": \"圆通快递\", " +
                " \"YUNDA\": \"韵达快递\", " +
                " \"OTHER\": \"其他\", " +
                " \"POST\": \"中国邮政\", " +
                " \"EMS\": \"EMS\", " +
                " \"FEDEX\": \"联邦快递\", " +
                " \"SHQ\": \"华强物流\", " +
                " \"TN\": \"特能\", " +
                " \"TAOBAO\": \"淘宝物流\", " +
                " \"ZTKY\": \"中铁物流\" " +
                " }";


        Map<String, String> params = JSONObject.parseObject(arr, new TypeReference<Map<String, String>>() {
        });

        JSONArray jsonArray = new JSONArray();

        params.forEach((code, name) -> {
            JSONObject object = new JSONObject();
            object.put("code", code);
            object.put("name", name);
            jsonArray.add(object);
        });

        return Result.buildResult(jsonArray);

    }


    @ApiOperation(value = "修改KS订单状态")
    @RequestMapping(value = "changeOrderStatus", method = RequestMethod.POST)
    public Result changeOrderStatus(@RequestBody ChangeOrderStatusRequest requests) {

        MyLambdaQueryWrapper<KsOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.eq(BaseEntity::getId, requests.getId());

        KsOrders ksOrders = ksOrdersService.getOne(queryWrapper);

        if (ksOrders == null) {
            return Result.buildResult(500, "订单不存在");
        }
        ksOrders.setPutLmStatus(requests.getPutLmStatus());
        if (StringUtils.isNotEmpty(requests.getAddress())) {
            ksOrders.setAddress(requests.getAddress());
        }

        ksOrdersService.updateById(ksOrders);
        return Result.buildResult();
    }


    @ApiOperation(value = "推送快递单号到ks")
    @RequestMapping(value = "putExpressToKs", method = RequestMethod.POST)
    public Result putExpressToKs(@RequestBody IdsRequest requests) {


        KsOrders ksOrders = ksOrdersService.getById(requests.getId());

        if (ksOrders == null) {
            return Result.buildResult(500, "订单存在！");
        }

        if (ksOrders.getPutLmStatus() == 0) {//推送lm状态 0未推送 1已推送 2推送失败
            return Result.buildResult(500, "订单未推送！");
        }

        if (ksOrders.getPutExpressStatus() == 1) {//推送物流状态 0未推送，1已经推送 2推送失败
            return Result.buildResult(500, "快递单号已经推送！");
        }

        if (ksOrders.getLmOrderId() == null) {//推送物流状态 0未推送，1已经推送 2推送失败
            return Result.buildResult(500, "lm单号为空！");
        }

        QueryLogisticsRequest request = new QueryLogisticsRequest();
        request.setBizId(LmConfig.LZ_BIZ_ID);
        request.setAccountType("ANONY");
        request.setThirdPartyUserId(ksOrders.getSellerId() + "");
        request.setBizUid(request.getThirdPartyUserId());
        request.setLmOrderId(Long.valueOf(ksOrders.getLmOrderId()));

        try {
            QueryLogisticsResponse response = client.getAcsResponse(request);

            System.out.println(response);

            if (response.getCode().equals("SUCCESS")) {
                List<QueryLogisticsResponse.DataItem> data = response.getData();
                QueryLogisticsResponse.DataItem item = data.get(0);

                if (item != null) {

                    if (!StringUtils.isNotEmpty(item.getMailNo())) {
                        return Result.buildResult(500, "快递单号不存在！");
                    }

                    GetLmOrderExpressResponse expressResponse = new GetLmOrderExpressResponse();
                    CopyUtils.copyProperties(item, expressResponse);

                    MyLambdaQueryWrapper<KsStoreUser> userWrapper = new MyLambdaQueryWrapper<>();

                    userWrapper.eq(KsStoreUser::getDelFlag, "0");

                    userWrapper.isNotNull(KsStoreUser::getKsSellerId);

                    userWrapper.eq(KsStoreUser::getKsSellerId, ksOrders.getSellerId());

                    KsStoreUser user = ksStoreUserService.getOne(userWrapper);

                    MyLambdaQueryWrapper<KsOauth> oauthWrapper = new MyLambdaQueryWrapper<>();

                    oauthWrapper.eq(KsOauth::getDelFlag, "0");

                    oauthWrapper.eq(KsOauth::getUserUuid, user.getUuid());

                    KsOauth ksOauth = ksOauthService.getOne(oauthWrapper);


                    AccessTokenKsMerchantClient tokenKsMerchantClient
                            = new AccessTokenKsMerchantClient("", KsConfigInfo.appKey, KsConfigInfo.signSecret);


                    /**
                     * 快递公司转换
                     */
                    ksOrders.setExpressNo(item.getMailNo());
                    ksOrders.setExpressName(item.getLogisticsCompanyName());
                    KsExpressCode expressCode = ksExpressCodeService.getOne(new MyLambdaQueryWrapper<KsExpressCode>().like(KsExpressCode::getName, item.getLogisticsCompanyName()));
                    if (expressCode != null) {
                        ksOrders.setExpressCode(expressCode.getCode());
                    }
                    /**
                     * 推送到ks
                     */
                    KsMerchantOrderDeliverRequest orderDeliverRequest = new KsMerchantOrderDeliverRequest();
                    orderDeliverRequest.setAccessToken(ksOauth.getAccessToken());
                    orderDeliverRequest.setOrderId(ksOrders.getOid());
                    orderDeliverRequest.setExpressCode(ksOrders.getExpressCode());
                    orderDeliverRequest.setExpressNo(ksOrders.getExpressNo());
                    KsMerchantOrderDeliverResponse deliverResponse = null;
                    try {
                        deliverResponse = tokenKsMerchantClient.execute(orderDeliverRequest);

                        System.out.println(deliverResponse.toString());

                        if (deliverResponse.getResult() == 1) {
                            ksOrders.setPutExpressStatus(1);
                        } else {
                            ksOrders.setPutExpressStatus(2);
                        }

                    } catch (KsMerchantApiException e) {
                        e.printStackTrace();
                    }
                    ksOrders.setKsErrMsg(JSON.toJSONString(response));

                    ksOrdersService.updateById(ksOrders);

                    return Result.buildResult(expressResponse);
                }

            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.buildResult(500, "快递单号不存在！");


    }


}
